package com.sphd.restaurantsystem.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.activitys.funding.FundingPersonageActivity;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.LoginInfo;
import com.sphd.restaurantsystem.info.RestaurantInfo;
import com.sphd.restaurantsystem.presenter.LoginPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.view.LoginView;
import com.wzh.frame.utils.MD5keyBean;
import com.wzh.frame.utils.MyUtils;
import com.wzh.frame.utils.StringUtils;

import org.litepal.crud.DataSupport;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 登录 程序入口
 */
public class LoginActivity extends BaseActivity implements LoginView {

    @BindView(R.id.btn_regist)
    TextView btnRegist;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.logon_name)
    MaterialEditText logonName;
    @BindView(R.id.pass_input)
    MaterialEditText passInput;
    @BindView(R.id.logon_btn)
    Button logonBtn;
    @BindView(R.id.forget_btn)
    Button forgetBtn;
    @BindView(R.id.remember_user)
    CheckBox rememberUser;
    private Intent intent;
    LoginPresenterImpl loginPresenter;
    boolean isremember = true;
    Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        addActivity(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        rememberUser.setOnCheckedChangeListener((compoundButton, b) -> isremember = b);
    }

    private void initView() {
        setTitleBar(toolbar, "登录");
        loginPresenter = new LoginPresenterImpl(this);
        intent = getIntent();
        if (intent.getStringExtra(Constant.TAG).equals(RegisterActivity.class.getSimpleName()) ||
                intent.getStringExtra(Constant.TAG).equals(ForgetPasswordActivity.class.getSimpleName())) {
            bundle = intent.getExtras();
            logonName.setText(bundle.getString(Constant.LOGINPHONE));
            passInput.setText(bundle.getString(Constant.LOGINPWD));
        } else {
            if (!StringUtils.isEmpty(String.valueOf(get(Constant.LOGINPHONE,"")))){
                logonName.setText(String.valueOf(get(Constant.LOGINPHONE,"")));
            }
            boolean isReme = (boolean) get(Constant.ISREMBER, false);
            if (isReme) {
                if (!StringUtils.isEmpty(String.valueOf(get(Constant.LOGINPWD,"")))){
                    passInput.setText(String.valueOf(get(Constant.LOGINPWD,"")));
                }
            }
        }
    }

    private void addData() {
        loginPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.Login + "username=" + logonName.getText().toString().trim() +
                "&userpwd=" + MD5keyBean.MD5(passInput.getText().toString().trim()) +
                "&userID=" + get(Constant.BAIDUUSERID, "userID") + "&channelID=" + get(Constant.ChannelID, "channelId") + "&deviceID=" +
                get(Constant.IMEI, "deviceID") + "&systemType=android");

    }


    @OnClick({R.id.btn_regist, R.id.logon_btn, R.id.forget_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_regist:
                startActivity(RegisterActivity.class);
                break;
            case R.id.logon_btn:
                checkNull();
                break;
            case R.id.forget_btn:
                startActivity(ForgetPasswordActivity.class);
                break;
        }
    }

    private void checkNull() {
        if (TextUtils.isEmpty(logonName.getText().toString().trim())) {
            logonName.setError("账号不能为空");
        } else {
            if (!MyUtils.isMobileNO(logonName.getText().toString().trim())) {
                logonName.setError("请输入正确的手机号码");
            } else {
                if (TextUtils.isEmpty(passInput.getText().toString().trim())) {
                    passInput.setError("密码不能为空");
                } else {
                    addData();
                }
            }
        }
    }

    @Override
    public void sendRes(LoginInfo loginInfo) {
        Log.e("3333==============", loginInfo.getStaff_auth() + "");

        if (loginInfo.getStaff_status() == 1) {
            if (loginInfo.getStaff_auth() == 2) {
                // TODO: 2016/10/31 以15522853307为例
                intent.setClass(context, SupperMeangerActivity.class);
            } else {
                Bundle bundle = new Bundle();
                RestaurantInfo restaurantInfo = new RestaurantInfo();
                restaurantInfo.setId(loginInfo.getStaff_cgid());
                bundle.putSerializable(Constant.RESTAURANTSINFO, restaurantInfo);
                intent.putExtras(bundle);
                if (loginInfo.getStaff_auth() == 6) {
                    // TODO: 2016/10/31 如果权限为6则跳转到众筹投资人界面
                    intent.setClass(context, FundingPersonageActivity.class);
                } else {
                    intent.setClass(context, UserHomeActivity.class);
                }
            }
            startActivity(intent);
            put(Constant.LOGINPHONE,logonName.getText().toString().trim());
            put(Constant.ISLOGIN, true);
            put(Constant.ISREMBER, isremember);
            put(Constant.LOGINPWD, passInput.getText().toString().trim());
            DataSupport.deleteAll(LoginInfo.class);
            loginInfo.save();
            finishActivity(this);
        } else {
            logonBtn.setEnabled(true);
            toast("账号审核中, 请稍后重试登录！");
        }
    }

    @Override
    public void sendCgNo(int cgnumber) {

    }

    @Override
    public void sendLcgid(int underlingcgid) {

    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }

    @Override
    public void sendPwdError() {
        toast("密码错误，请重试！");
    }

    @Override
    public void sendServiceError() {
        toast("服务器连接错误，请稍后重试！");
    }
}
